package com.service.sale;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.sale.ContractDraftDao;
import com.dao.sale.ContractSignDao;
import com.dao.sys.SysUserRoleMapper;
import com.model.sale.ContractSignModel;
import com.model.sale.ContractVOModel;
import com.model.sys.SysUser;
import com.service.external.oa.GetWFStatusService;
import com.service.external.sap.SaleService;

@Service
public class ContractSignService {
	static final Logger logger = LoggerFactory.getLogger(ContractSignService.class);

	@Autowired
	ContractSignDao contractSignDao;
	@Autowired
	GetWFStatusService getWFStatusService;
	@Autowired
	ContractDraftService contractDraftService;
	@Autowired
	SaleService saleService;
	@Autowired
	ContractDraftDao contractDraftDao;
	@Autowired
	SysUserRoleMapper sysUserRoleMapper;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		/*
		 * queryMap.put("isAdmin", "N"); SysUser sysUser = SpringMvcUtils.getSysUser();
		 * if (null != sysUser) { SysRole sysRole =
		 * contractDraftDao.selectRoleByRoleName("管理员"); List<SysUserRole> sysUserRoles
		 * = sysUserRoleMapper.selectAllByUserid(sysUser.getUserid()); if
		 * (!CollectionUtils.isEmpty(sysUserRoles)) { for (SysUserRole sysUserRole :
		 * sysUserRoles) { if (sysUserRole.getRoleid().equals(sysRole.getRoleid())) {
		 * queryMap.put("isAdmin", "Y"); break; } } } queryMap.put("createId",
		 * sysUser.getUserid()); }
		 */
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<ContractSignModel> list = contractSignDao.selectList(queryMap);
		int count = contractSignDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 *
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String sigId) {
		HttpResult httpResult = new HttpResult();
		ContractSignModel contractSignModel = contractSignDao.load(sigId);
		httpResult.setData(contractSignModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(ContractSignModel contractSignModel) {
		if (contractSignModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		SysUser sysUser = SpringMvcUtils.getSysUser();
		int result = 0;
		String draId = contractSignModel.getDraId();
		HttpResult draftResult = contractDraftService.selectInfor(draId);
		ContractVOModel contractVOModel = new ContractVOModel();
		if (null != draftResult) {
			contractVOModel = (ContractVOModel) draftResult.getData();
		}
		// 提交
		if (contractSignModel.getStatus().equals(Global.YES + "")) {
			// 当前提交日期<=(计划完成发货日期-5天），不允许提交
			// 如果不为空，则表示该产品为远期定价产品
			String planStartDeliveryDate = contractVOModel.getDraPlanCompleteDeliveryTime();
			if (!StringUtils.isNullOrEmpty(planStartDeliveryDate)) {
				Date d = new Date();
				String current = DateUtils.convertDateToString(DateUtils.addDays(d, 5));
				if (current.compareTo(planStartDeliveryDate) < 0) {
					return HttpResult.error("未到合同约定发货时间，不允许提交！");
				}
			}

			contractVOModel.seteRDATB(contractVOModel.getCreateTime());
			contractVOModel.seteRDATA(contractSignModel.getCreateTime());
			// 判断OA流程是否走完
			if (null != contractVOModel) {
				HttpResult oaHttpResult = getWFStatusService.getWFStatus(contractVOModel.getOaWfId() + "",
						sysUser.getWxid());
				if (oaHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error("oa流程未审批结束！");
				} else {
					JSONObject workFlowResult = JSONObject.parseObject(JSON.toJSONString(oaHttpResult.getData()));
					JSONObject out = workFlowResult.getJSONObject("out");
					JSONArray workFlowInfos = out.getJSONArray("workflowRequestInfo");
					JSONObject workFlowInfo = workFlowInfos.getJSONObject(0);
					contractVOModel.seteRDATB(StringUtils.isNotNull(workFlowInfo.getString("createTime"))
							? workFlowInfo.getString("createTime")
							: contractVOModel.getCreateTime());
					contractVOModel.seteRDATA(StringUtils.isNotNull(workFlowInfo.getString("lastOperateTime"))
							? workFlowInfo.getString("lastOperateTime")
							: contractSignModel.getCreateTime());
				}
			}
			// 调用SAP接口
			HttpResult sapHttpResult = saleService.createSapSale(contractVOModel);
			if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
				// 强制手动事务回滚
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error("SAP系统信息：" + sapHttpResult.getMsg());
			} else {
				if (null != sapHttpResult.getData()) {
					String resultData = sapHttpResult.getData().toString();
					String[] codeArr = resultData.split("/");
					if (codeArr.length > 1) {
						contractSignModel.setPoNumber(codeArr[1]);
					}
				}
			}
		}
		if (!StringUtils.isNotNull(contractSignModel.getSigId())) {
			contractSignModel.setSigId(UUID.randomUUID().toString());
			result = contractSignDao.insert(contractSignModel);
		} else {
			result = contractSignDao.update(contractSignModel);
		}
		if (result > 0) {
			if (contractSignModel.getStatus().equals(Global.YES + "")) {
				contractVOModel.setTransedSap("1");
				contractVOModel.setStatus(Global.NUMERICAL_TWO + "");
				contractDraftDao.update(contractVOModel);
				httpResult.setMsg("提交成功!");
			} else {
				httpResult.setMsg("保存成功!");
			}
			httpResult.setData(contractSignModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(contractSignModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 保存长约合同签署
	 *
	 * @param contractSignModel
	 * @return
	 */
	@Transactional
	public HttpResult saveLong(ContractSignModel contractSignModel) {
		if (contractSignModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		SysUser sysUser = SpringMvcUtils.getSysUser();
		int result = 0;
		String draId = contractSignModel.getDraId();
		if (!StringUtils.isNotNull(contractSignModel.getSigId())) {
			// 根据原虚拟合同号，查询该长约合同是否在长约签署列表中
			ContractSignModel signContract = contractSignDao.selectByDraId(draId);
			if (null != signContract) {
				return HttpResult.error("长约合同号 " + signContract.getDraCode() + "已在签署列表中存在!");
			}
			contractSignModel.setSigId(UUID.randomUUID().toString());
			result = contractSignDao.insert(contractSignModel);
		} else {
			result = contractSignDao.update(contractSignModel);
		}

		HttpResult draftResult = contractDraftService.selectInfor(draId);
		ContractVOModel contractVOModel = new ContractVOModel();
		if (null != draftResult) {
			contractVOModel = (ContractVOModel) draftResult.getData();
		}
		// 提交
		if (contractSignModel.getStatus().equals(Global.YES + "")) {
			// 判断OA流程是否走完
			if (null != contractVOModel) {
				if (getWFStatusService.getWFStatus(contractVOModel.getOaWfId() + "", sysUser.getWxid())
						.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error("oa流程未审批结束！");
				}
			}

			// 调用SAP修改价格接口
			HttpResult sapHttpResult = saleService.modifiSapContractPrice(contractVOModel);
			if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
				// 强制手动事务回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error("SAP系统信息：" + sapHttpResult.getMsg());
			}
		}

		if (result > 0) {
			if (contractSignModel.getStatus().equals(Global.YES + "")) {
				contractVOModel.setTransedSap("1");
				contractVOModel.setStatus(Global.NUMERICAL_TWO + "");
				contractDraftDao.update(contractVOModel);
				httpResult.setMsg("提交成功!");
			} else {
				httpResult.setMsg("保存成功!");
			}
			httpResult.setData(contractSignModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(contractSignModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String sigId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(sigId)) {
			return HttpResult.error("参数不能为空");
		}
		int result = contractSignDao.delete(sigId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 *
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<ContractSignModel> list = contractSignDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), ContractSignModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
